package top.frsf;

import top.frsf.bullets.BulStart;
import top.frsf.card.CardStart;
import top.frsf.envi.EnvStart;
import top.frsf.envi.zombieAubio;
import top.frsf.input.MouseCont;
import top.frsf.plants.PlaStart;
import top.frsf.utils.GameState;
import top.frsf.zombies.ZomStart;

import javax.swing.*;
import java.awt.*;
import java.util.Timer;
import java.util.TimerTask;

/**
 * @BelongsProject: MiniPZ
 * @BelongsPackage: top.frsf
 * @Author: FRSF
 * @CreateTime: 2022-09-06  12:54
 * @Description: 游戏面板
 * @Version: 1.0
 */
public class GamePanel extends JFrame {
    // 游戏窗体尺寸
    public static final int WIDTH = 900;
    public static final int HEIGHT = 630;

    // 游戏重绘定时器
    private final java.util.Timer timer = new Timer();

    // 游戏状态枚举
    public static GameState stage = GameState.HOME;

    // 图片全局处理器
    public static final Toolkit tKit = Toolkit.getDefaultToolkit();

    // 全局fps
    public static long fps = 0L;


    /* 场景启动器 */
    // 环境
    public static final EnvStart envStart = new EnvStart();
    // 植物
    public static final PlaStart plaStart = new PlaStart();
    // 卡片
    public static final CardStart cardStart = new CardStart();
    // zom
    public static final ZomStart zomStart = new ZomStart();
    // 子弹
    public static final BulStart bulStart = new BulStart();


    /* 游戏加载启动 */
    public void launch() {
        // 窗体参数初始化
        setSize(WIDTH, HEIGHT);
        setTitle("MiniPZ");
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setResizable(false);
        setVisible(true);

        // 新线程播放音乐
        Runnable music = new zombieAubio("src/main/resources/envi/music/bgm.wav");
        Thread t = new Thread(music);
        t.start();

        // 添加鼠标操作, 坑：
        //  this.addMouseListener()是添加鼠标监视，addMouseMotionListener()是添加鼠标运动监视
        MouseCont mouseCont = new MouseCont();
        this.addMouseListener(mouseCont);
        this.addMouseMotionListener(mouseCont);

        // 定时添加阳光
        envStart.SunTimerTask();

        // 定时重绘
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                repaint();
            }
        }, 1000, 10);
    }


    /* 游戏画面绘制 */
    @Override
    public void paint(Graphics g) {

        // 双缓存机制
        Image flashImage = this.createImage(WIDTH, HEIGHT);
        Graphics flashG = flashImage.getGraphics();

        if (stage == GameState.HOME) {
            envStart.home.paintSelf(flashG);
        } else if (stage == GameState.START || stage == GameState.RUNNING) {
            envStart.paintEnvi(flashG);
            cardStart.paintCard(flashG);
            plaStart.paintPla(flashG);
            zomStart.paintZom(flashG);
            bulStart.paintBullet(flashG);
        }

        fps++;
        g.drawImage(flashImage, 0, 0, null);
    }
}
